<template>
  <div>
    <van-cell
      v-for="(item, index) in hightLightSuggestions"
      :key="index"
      icon="search"
      @click="$emit('updata-keywords', suggestions[index])"
    >
      <template #title>
        <span v-html="item"></span>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestionsAPI } from '@/api'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestions',
  props: {
    keywords: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestions: []
    }
  },
  watch: {
    // 监事属性的字符串写法 ，会自动去methods里面找同名方法调用
    keywords: {
      handler: 'getSearchSuggestions',
      // 在创建组件的时候 直接调用一次
      immediate: true
    }
  },
  computed: {
    // map 返回值是一个新数组
    // 动态 正则 new RegExp()
    // - 字面量正则 /a/ 缺点：公式写死了
    // - 动态正则 new RegExp(正则内容字符串可以写变量，修饰字符串)

    // 字符串的replace
    // 返回值：替换的新字符串
    hightLightSuggestions() {
      const reg = new RegExp(this.keywords, 'ig')
      return this.suggestions.map((item) => {
        return item.replace(
          reg,
          (match) => `<span style='color:red'>${match}</span>`
        )
      })
    }
  },
  methods: {
    getSearchSuggestions: debounce(async function () {
      //  防抖处理
      const { data } = await getSuggestionsAPI(this.keywords)
      // this.suggestions = data.data.options.filter((item) => item !== null)
      // this.suggestions = data.data.options.filter((item) => !!item)
      // this.suggestions = data.data.options.filter((item) => Boolean(item))
      this.suggestions = data.data.options.filter(Boolean)
    }, 300)
  }
}
</script>

<style scoped lang="less"></style>
